package com.leyou.auth.config;

import com.leyou.auth.client.AuthClient;
import com.leyou.utils.JwtUtil;
import feign.FeignException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

/**
 * @author jshstart
 * @creat 2020-12-23 19:35
 */
@Configuration
@Slf4j
@EnableConfigurationProperties(ClientProperties.class)
//确保调用auth接口的微服务的yml文件必须有前缀为ly.auth的配置，配置名必须和下面的一样
@ConditionalOnProperty(prefix = "ly.auth",name = {"clientId","secret"})
//引入编写client，便于查找密匙
@EnableFeignClients(basePackages = "com.leyou.auth.client")
public class AuthConfiguration {
    private AuthClient authClient;
    private ClientProperties properties;

    public AuthConfiguration(AuthClient authClient, ClientProperties properties) {
        this.authClient = authClient;
        this.properties = properties;
    }
    @Bean
    @Primary
    public JwtUtil jwtUtil(){
        while (true){
            try {
                String key = authClient.getSecretKey(properties.getClientId(), properties.getSecret());
                JwtUtil jwtUtil = new JwtUtil(key);
                log.info("密匙加载成功");
                return jwtUtil;
            } catch (FeignException e) {
                // 加载秘钥失败，5秒后重试
                log.error("加载jwt秘钥失败了。原因： {}", e.contentUTF8());
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException interruptedException) {
                    interruptedException.printStackTrace();
                }
            }
        }
    }

}
